package com.yanghui.eletask4.core

import com.yanghui.eletask4.HeartWaveData
import com.yanghui.eletask4.LogOutData
import com.yanghui.eletask4.LoginData
import com.yanghui.eletask4.SportData
import com.yanghui.eletask4.activity.MainActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.InputStream
import java.net.ServerSocket
import java.net.Socket
import java.util.*

class TCPServer(private val port: Int) {

    val socketArray = LinkedList<Socket>()
    val serverSocket: ServerSocket = ServerSocket(port)

    fun run() {
        GlobalScope.launch(Dispatchers.IO) {
            while (true) {
                val socket = serverSocket.accept()
                socketArray.add(socket)
                GlobalScope.launch(Dispatchers.IO) {
                    val inputStream: InputStream = socket.getInputStream()
                    val buff: ByteArray = ByteArray(4096)
                    var receiveLen: Int = 0
                    try {
                        while (!socket.isClosed && !socket.isInputShutdown) {
                            var sportDataCache = SportData("")
                            receiveLen = inputStream.read(buff)
                            if (receiveLen != -1) {
                                val messageChain = String(buff, 0, receiveLen)
                                messageChain.split("&").forEach {
                                    if (it.isNotBlank()) {
                                        if (it.startsWith("L")) {
                                            MainActivity.messageChannel.send(LoginData(it))
                                        } else if (it.startsWith("W")) {
                                            MainActivity.messageChannel.send(HeartWaveData(it))
                                        } else {
                                            sportDataCache = SportData(it, sportDataCache)
                                            MainActivity.messageChannel.send(SportData(it))
                                        }
                                    }
                                }
                            } else {
                                break
                            }
                        }
                    } catch (e: Exception) {
                        MainActivity.messageChannel.send(LogOutData())
                    }
                }
            }
        }
    }
}